import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
  Dimensions,
  Pressable,
  SafeAreaView,
  SectionList,
  StyleSheet,
  Text,
  View,
} from "react-native";
import { SearchScreenProps } from "../../types/NavigationTypes";
import SearchBarView from "../../components/SearchBarView";
import apiService from "../../services/ApiServices";

import { FlatGrid } from "react-native-super-grid";
import PipeListItem from "../../components/PipeListItem";
import Icon from "react-native-vector-icons/Feather";
import AsyncStorageHelper from "../../helpers/asyncStorageHelper";
import SearchContent from "../../components/SearchContent";

const screenWidth = Dimensions.get("window").width;
const SEARCH_RECORD_KEY = "SearchRecordList";

interface SearchBarViewRef {
  updateSearchText: (text: string) => void;
}

const SearchScreen: React.FC<SearchScreenProps> = ({ navigation }) => {
  const [searchRecordList, setSearchRecordList] = useState<string[]>([]);
  const [hotSearchList, setHotSearchList] = useState([]);
  const [recommendPipeList, setRecommendPipeList] = useState([]);
  const [itemHeight, setItemHeight] = useState<number>(0);

  const [showSearchResult, setShowSearchResult] = useState(false);
  const [searchText, setSearchText] = useState('');

  const hotSearchListRef = useRef([]);
  const searchRef = useRef<SearchBarViewRef>(null);

  useEffect(() => {
    const width = (screenWidth - 24.0) * 0.5;
    const height = 70 + (width * 16) / 11;
    setItemHeight(height);
  }, []);

  useEffect(() => {
    getSearchRecordList();
  }, []);

  const getSearchRecordList = async () => {
    const data = await AsyncStorageHelper.getStringList(SEARCH_RECORD_KEY);
    setSearchRecordList(data || []);
  };

  const updateSearchText = (text: string) => {
    if (searchRef.current) {
      searchRef.current.updateSearchText(text);
    }
  };

  const _addSearchRecord = async (tag: string) => {
    if (tag == null || tag === '') return;
    updateSearchText(tag);
    const list = searchRecordList.filter((item) => item !== tag);
    list.unshift(tag);
    setSearchRecordList(list);
    await AsyncStorageHelper.setStringList(SEARCH_RECORD_KEY, list);

    _onSearch(tag);
  };

  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: () => <SearchBarView ref={searchRef} onSearch={_onSearch} />,
      headerTitleAlign: "left",
      headerBackVisible: false,
    });
  }, [navigation]);

  const _onSearch = async (text: string) => {
    if (text == null || text === '') return;
    setSearchText(text);
    setShowSearchResult(true);
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result1 = await apiService.getSearchHotWordList();
        const result2 = await apiService.getRecommendPipeList();
        hotSearchListRef.current = result1?.data || [];
        const data =
          hotSearchListRef.current.length > 6
            ? hotSearchListRef.current.slice(0, 6)
            : hotSearchListRef.current;
        setHotSearchList(data);
        setRecommendPipeList(result2?.data || []);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);

  const _renderItem = ({ item }: any) => {
    return <PipeListItem item={item} itemHeight={itemHeight} />;
  };

  const sections = [
    {
      key: "0",
      title: "历史记录",
      data: [searchRecordList],
      renderItem: ({ item }: any) => (
        <View style={styles.wrapContainer}>
          {item.map((tag: any) => (
            <Pressable
              onPress={async () => {
                await _addSearchRecord(tag);
              }}
            >
              <View style={styles.tagItem}>
                <Text style={{ fontSize: 13 }}>{tag}</Text>
              </View>
            </Pressable>
          ))}
        </View>
      ),
    },

    {
      key: "1",
      title: "猜你想搜",
      data: [hotSearchList],
      renderItem: ({ item }: any) => (
        <View style={styles.wrapContainer}>
          {item.map((tag: any) => (
            <Pressable
              onPress={async () => {
                await _addSearchRecord(tag);
              }}
            >
              <View style={styles.tagItem}>
                <Text style={{ fontSize: 13 }}>{tag}</Text>
              </View>
            </Pressable>
          ))}
        </View>
      ),
    },

    {
      key: "2",
      title: "热门推荐",
      data: [recommendPipeList],
      renderItem: ({ item }: any) => (
        <FlatGrid
          spacing={8}
          itemDimension={(screenWidth - 24) / 2}
          data={item}
          renderItem={_renderItem}
          scrollEnabled={false}
        />
      ),
    },
  ];

  const _refreshHotSearch = () => {
    hotSearchListRef.current.sort(() => Math.random() - 0.5);
    const data =
      hotSearchListRef.current.length > 6
        ? hotSearchListRef.current.slice(0, 6)
        : hotSearchListRef.current;
    setHotSearchList(data);
  };

  return (
    <View style={{ flex: 1 }}>
      
      {showSearchResult ? (
        <SafeAreaView style={{ flex: 1, backgroundColor: "#fff" }}>
           <SearchContent searchText={searchText}/>
        </SafeAreaView>
      ) : (
        <SectionList
          style={{ backgroundColor: "white" }}
          sections={sections}
          renderSectionHeader={({ section: { title, key } }) => {
            if (key === "0") {
              if (searchRecordList.length > 0) {
                return (
                  <View style={styles.sectionHeader}>
                    <Text style={styles.sectionTitle}>{title}</Text>
                  </View>
                );
              } else {
                return null;
              }
            } else if (key === "1") {
              return (
                <View style={styles.sectionHeader}>
                  <Text style={styles.sectionTitle}>{title}</Text>
                  <Pressable onPress={_refreshHotSearch}>
                    <Icon name="refresh-ccw" size={16} color="#999" />
                  </Pressable>
                </View>
              );
            }
            return (
              <View style={styles.sectionHeader}>
                <Text style={styles.sectionTitle}>{title}</Text>
              </View>
            );
          }}
          keyExtractor={(_, index) => index.toString()}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  wrapContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    paddingHorizontal: 10,
    backgroundColor: "white",
  },
  tagItem: {
    padding: 8,
    borderRadius: 20,
    margin: 4,
    borderColor: "rgba(0,0,0,0.08)",
    borderWidth: 1,
  },
  sectionHeader: {
    backgroundColor: "#fff",
    padding: 10,
    flexDirection: "row",
    justifyContent: "space-between",
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "bold",
  },
});

export default SearchScreen;
